import GameControl2 from "./GameControl2";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GoLuckDraw2 extends cc.Component {

    public CompleteCallBack: () => void;

    private EndDarwTick: number = 2;    //最后一轮的秒数为2秒;
    private CurIndex: number;           //起始位置
    private StopIndex: number;          //停止位置
    private Allticks: number;           //总秒数
    private MaxCount: number;           //轮数

    private MainThis: GameControl2;

    onLoad() {

    }

    /**
     * 
     * @param curIndex   起始位置
     * @param stopIndex  结束位置
     * @param allticks   总时长
     * @param maxCount      轮次
     */
    public StartLuckDraw(gameControl: GameControl2, curIndex: number, stopIndex: number, allticks: number, maxCount: number) {
        this.MainThis = gameControl;

        this.CurIndex = curIndex;
        this.StopIndex = stopIndex + this.MainThis.rewardCount;
        this.Allticks = allticks > 3 ? allticks : 3;
        this.MaxCount = maxCount;

        this.LuckDrawRounds();
    }

    private async LuckDrawRounds() {
        let time1 = 0, time2 = 0;
        let sumCount = this.MaxCount * this.MainThis.rewardCount;
        let avgTime = (this.Allticks - this.EndDarwTick) / sumCount;  //平均时间

        for (let i = this.CurIndex; i < sumCount; i++) {
            time1 = cc.misc.lerp(0, avgTime * 2, (1 / sumCount) * (i + 1));

            this.SetAwardState(i);
            await this.SleepTime(time1);
        }

        avgTime = this.EndDarwTick / this.StopIndex;
        for (let i = 0; i < this.StopIndex; i++) {
            time2 = cc.misc.lerp(time1, avgTime * 2, (1 / this.StopIndex) * (i + 1));

            this.SetAwardState(i);
            await this.SleepTime(time2);
        }
        this.SetAwardState(this.StopIndex);

        await this.SleepTime(1);

        if (this.CompleteCallBack != null) {
            this.CompleteCallBack();
        }
    }

    private SleepTime(time: number): Promise<void> {
        return new Promise((resolve, reject) => {
            this.scheduleOnce(() => {
                resolve();
            }, time);
        })
    }

    private SetAwardState(index: number) {
        let _index = index % this.MainThis.rewardCount;

        let label: cc.Node;
        let lastIndex = _index - 1 < 0 ? this.MainThis.rewardCount - 1 : _index - 1;
        label = this.MainThis.AwardNode.children[lastIndex]?.getChildByName("label");
        if (label) {
            label.color = cc.Color.WHITE;
        }

        label = this.MainThis.AwardNode.children[_index]?.getChildByName("label");
        if (label) {
            label.color = cc.Color.RED;
        }
    }
}